//
//  ZLNumberExtension.swift
//  ZLExtension
//
//  Created by 科大 on 2025/1/3.
//

import Foundation

public extension Int {
    /// 时
    func zl_hour() -> Int {
        return self / 3600
    }
    /// 分
    func zl_minute() -> Int {
        return self % 3600 / 60
    }
    /// 秒
    func zl_second() -> Int {
        return self % 60
    }
}

// MARK: 适配
public extension BinaryFloatingPoint {
    /// 适应屏幕比例
    var fit: Self {
        let fit = self / 375.0 * Self(UIScreen.zl_width())
        let fractional = fit - fit.rounded(.down)
        if fractional > 0.5 {
            return fit.rounded(.up)
        } else {
            return fit.rounded(.down)
        }
    }
    /// 取整, 余数大于0.5向上取整,否者详细取整
    var zl_round: Int {
        let decimal = self - floor(self)
        if decimal > 0.5 {
            return Int(self.rounded(.up))
        } else {
            return Int(self.rounded(.down))
        }
    }
    /// 取最近的数
    func zl_nearest(in array: [Self]) -> Self {
        guard array.first != nil else { return self }
        return array.min(by: { abs($0 - self) < abs($1 - self) }) ?? self
    }
    /// 取最近比自己大的数
    func zl_nearestUp(in array: [Self]) -> Self {
        let largerValues = array.filter { $0 >= self }
        return largerValues.min(by: { abs($0 - self) < abs($1 - self) }) ?? self
    }
    /// 取最近比自己小的数
    func zl_nearestDown(in array: [Self]) -> Self {
        let smallerValues = array.filter { $0 <= self }
        return smallerValues.max(by: { abs($0 - self) < abs($1 - self) }) ?? self
    }
    /// 保留指定位数
    /// - Parameter digits: 位数
    func zl_digits(digits: Int) -> Self {
        let numberFormatter = NumberFormatter()
        numberFormatter.maximumFractionDigits = digits // 设置最多两位小数
        numberFormatter.minimumFractionDigits = digits // 设置至少两位小数
        if let formattedString = numberFormatter.string(from: NSNumber(value: Double(self))) {
            let finalValue = CGFloat((formattedString as NSString).doubleValue)
            return Self(finalValue)
        }
        return self
    }
}

public extension Int {
    var fit: CGFloat {
        return CGFloat(self).fit
    }
}
